package com.novabluetooth.views;

import java.util.ArrayList;
import java.util.List;

import com.blankj.utilcode.util.AdaptScreenUtils;
import com.ebelter.sdks.managers.ScaleManager;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.tablebean.BTDevice;
import com.health.tools.SPUtil;
import com.nova.BaseActivity;
import com.novabluetooth.adapter.BlueToothDeviceAdapter;
import com.novabluetooth.services.BluetoothConstant;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 蓝牙设备绑定
 *
 * @author nova
 */
public class BluetoothDeviceBindActivity2 extends BaseActivity
        implements OnItemClickListener, OnItemLongClickListener, android.view.View.OnClickListener {
    /* 取得默认的蓝牙适配器 */
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();
    /* 用来存储搜索到的蓝牙设备 */
    private List<BluetoothDevice> _devices = new ArrayList<BluetoothDevice>();
    /* 是否完成搜索 */
    private List<BTDevice> scanList = new ArrayList<BTDevice>();
    private List<BTDevice> savedList = new ArrayList<BTDevice>();
    com.health.db.FDbManager fdbmanger = NovaApplication.fdbmanger;
    private ListView saveListView;
    private ListView scanListView;
    private BlueToothDeviceAdapter savedAdapter;
    private BlueToothDeviceAdapter scanAdapter;
    private Button fanhui;
    private Button save;
    BluetoothAdapter mBluetoothAdapter;// ble
    BluetoothManager mBluetoothManager;
    // private BluetoothAdapter mBluetoothAdapter2;// 蓝牙2.0
    private static final long SCAN_PERIOD = 60000;
    RadioGroup ew_group;
    RadioButton ew_button2;
    RadioButton ew_button4;

    @Override
    public Resources getResources() {
        return AdaptScreenUtils.adaptWidth(super.getResources(), 840);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.bluetooth_sbcl_bind_discovery);

        try {
            saveListView = (ListView) findViewById(R.id.bluetooth_saved_lv);
            scanListView = (ListView) findViewById(R.id.bluetooth_scan_lv);
            fanhui = (Button) findViewById(R.id.btn_back);
            fanhui.setOnClickListener(this);
            LinearLayout ll_finish = (LinearLayout) findViewById(R.id.ll_finish);
            TextView tv_title = (TextView) findViewById(R.id.tv_title);
            save = (Button) findViewById(R.id.btn_up);
            ew_group = (RadioGroup) findViewById(R.id.ew_group);
            ew_button2 = (RadioButton) findViewById(R.id.ew_button2);
            ew_button4 = (RadioButton) findViewById(R.id.ew_button4);
            RadioButton rb_yb = (RadioButton) findViewById(R.id.rb_yb);
            RadioButton rb_search = (RadioButton) findViewById(R.id.rb_search);
            rb_yb.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    saveListView.setVisibility(View.VISIBLE);
                    scanListView.setVisibility(View.GONE);
                }
            });
            rb_search.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    saveListView.setVisibility(View.GONE);
                    scanListView.setVisibility(View.VISIBLE);
                }
            });
            if (SPUtil.getisBlooth2(BluetoothDeviceBindActivity2.this, false)) {
                ew_button2.setChecked(true);
                ew_button4.setChecked(false);
            } else {
                ew_button2.setChecked(false);
                ew_button4.setChecked(true);
            }
            ll_finish.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    finish();
                }
            });
            tv_title.setText("蓝牙设备绑定");
            findViewById(R.id.bt_save).setVisibility(View.GONE);
            scanListView.setOnItemClickListener(this);
            saveListView.setOnItemClickListener(this);
            saveListView.setOnItemLongClickListener(this);
            showList();

            initBlooth();

            scanLeDevice(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void setHeadTitle(String title, View head) {
        TextView tv = (TextView) head.findViewById(R.id.bluetooth_head_tv);
        tv.setText(title);
    }

    @Override
    protected void onDestroy() {
        Log.w("TAG", "onDestroy");
        scanLeDevice(false);

        boolean isBlooth2;

        if (ew_button2.isChecked()) {
            isBlooth2 = true;
        } else {
            isBlooth2 = false;
        }
        SPUtil.setisBlooth2(BluetoothDeviceBindActivity2.this, isBlooth2);
        super.onDestroy();
    }

    private void showList() {
        savedList = new ArrayList<>();
        savedList = fdbmanger.findAllBT(BTDevice.class);
        savedAdapter = new BlueToothDeviceAdapter(this, savedList);
        saveListView.setAdapter(savedAdapter);

        scanList = new ArrayList<>();
        scanAdapter = new BlueToothDeviceAdapter(this, scanList);
        scanListView.setAdapter(scanAdapter);

    }

    /* 显示列表 */
    protected void showScanDevices() {
        scanList = new ArrayList<>();
        for (int i = 0, size = _devices.size(); i < size; ++i) {
            BluetoothDevice d = _devices.get(i);
            BTDevice device = new BTDevice();
            Log.i("nova", d.getName());
            String novaName = BluetoothConstant.getNovaDevice(d.getName());
            if (TextUtils.isEmpty(novaName)) {
                return;
            }
            device.setName(novaName);
            device.setMacAddress(d.getAddress());
            if (!scanList.contains(device)) {

                Log.e("TAG", device.getName() + "#####");
                scanList.add(device);

            }
        }
        scanAdapter = new BlueToothDeviceAdapter(this, scanList);
        scanListView.setAdapter(scanAdapter);
        scanAdapter.notifyDataSetChanged();
        scanLeDevice(true);
    }

    private boolean isSavedDevice(BTDevice device, List<BTDevice> list) {
        boolean isSaved = false;
        if (list.size() < 0) {
            return isSaved;
        }
        for (BTDevice btDevice : list) {
            if (btDevice.equals(device)) {
                isSaved = true;
                break;
            }
        }
        return isSaved;
    }

    @SuppressLint("WrongConstant")
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.e("TAG", "点击了:" + position);

        if (parent.equals(saveListView)) {
            BTDevice savedDevice = savedList.get(position);
        } else if (parent.equals(scanListView)) {
            getNewSavedList();
            BTDevice device = scanList.get(position);
            if (!isSavedDevice(device, savedList)) {
                Log.e("xiaoxin", "onItemClick: " + device.getName() + device.getMacAddress());
                fdbmanger.saveBT(device);
                savedList.add(device);
                savedAdapter.setInfoList(savedList);
                savedAdapter.notifyDataSetChanged();
                Toast.makeText(this, "已绑定设备：" + device.getName(), 0).show();
            } else {
                Toast.makeText(this, "设备已存在", 0).show();
            }
        }

    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {

        new AlertDialog.Builder(this).setTitle("确认删除").setMessage("确定删除所选项吗？")
                .setPositiveButton("删除", new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getNewSavedList();
                        BTDevice btDevice = savedList.get(position);
                        fdbmanger.deleteBT(btDevice);
                        savedList.remove(btDevice);
                        savedAdapter.setInfoList(savedList);
                        savedAdapter.notifyDataSetChanged();

                    }
                }).setNegativeButton("取消", null).show();

        return true;
    }

    private void getNewSavedList() {
        savedList = fdbmanger.findAllBT(BTDevice.class);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_back) {
            finish();
        } else {
        }

    }

    /**
     * 初始化蓝牙信息
     *
     * @author 王婷婷
     * @date 2015年12月18日 上午10:41:48
     */
    private void initBlooth() {
        System.out.println("00000000000000000");
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Log.w("noticeservice-----", "手机不支持BLE");
        }

        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        // mBluetoothAdapter2 = BluetoothAdapter.getDefaultAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Log.w("noticeservice-222----", "手机不支持蓝牙");
        }
        Log.w("noticeservice--tt----", "手机支持蓝牙");
        // 开启蓝牙
        if (!mBluetoothAdapter.isEnabled()) {
            boolean flag = mBluetoothAdapter.enable();
            // 开启蓝牙成功还是失败
            if (flag) {
                NovaApplication.isBluetoothOpen = true;
            } else {
                NovaApplication.isBluetoothOpen = false;
            }

        } else {
            NovaApplication.isBluetoothOpen = true;
        }

    }

    public void scanLeDevice(final boolean enable) {
        try {
            if (enable) {
                System.out.println("开始检测 ");
                Log.w("开始检测", "正在搜索检测设备");
                mBluetoothAdapter.startLeScan(mLeScanCallback);
            } else {
                Log.w("扫描失败", "扫描设备失败");
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            try {
                if (device.getName() != null) {
                    Log.e("TAG", device.getName());
                    Log.w("TAG", "device.getName():" + device.getName());
                    // 不是设备列表中的数据继续扫描
                    String novaName = BluetoothConstant.getNovaDevice(device.getName());
                    if (device.getName().length() > 9) {
                        String subName = device.getName().substring(0, 9);
                        Log.e("TAG", "获取前九位：" + subName);
                        if (subName.equals("BeneCheck")) {
                            novaName = device.getName();
                        }
                    }
                    if (TextUtils.isEmpty(novaName)) {
                        return;
                    }
                    /* 将结果添加到列表中 */
                    if (!scanList.contains(device)) {
                        /* 显示列表 */
                        Log.w("TAG", device.getName() + "*****************");
                        _devices.add(device);
                        scanLeDevice(false);
                        runOnUiThread(new Runnable() {
                            public void run() {
                                showScanDevices();
                            }
                        });
                    } else {
                        scanLeDevice(true);
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };

    // 捕获返回键的方法1
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            // 按下BACK，同时没有重复
            finish();
        }

        return super.onKeyDown(keyCode, event);
    }

}
